﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BJ.AuthEntity.ViewModels;
using Syspetro.Core.AppDeal;
using Syspetro.Core.DynamicApi;
using Syspetro.Deploy.Jwt;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
using BJ.AuthDomain.IService;
using Syspetro.Deploy.AuthorizationReq;
using Microsoft.Extensions.Localization;
using Syspetro.Core.Localization;
using Syspetro.Core.Resources;
using Syspetro.Core.Extensions;
using BJ.AuthDomain.Service;
using Syspetro.Core.AopService;
using BJ.MallDomain.RemotService;

namespace BJ.AuthApp
{
    /// <summary>
    /// Api权限中心
    /// </summary>
    public class Authentication : BaseDynamicApi
    {
        private readonly IUserAuthService _AuthService;
        private readonly IAppMService _appMService;

        public Authentication(IUserAuthService authService, IAppMService appMService)
        {
            _AuthService = authService;
            _appMService = appMService;

        }
        /// <summary>
        /// 用户登录(简单验证用户名和密码)
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_Token>> Login([FromBody] VM_Login loginUser)
        {
            var token = await _AuthService.LoginUser(loginUser);
            if (token != null)
            {
                return token;
            }
            else
            {
                return Fail<VM_Token>(SharedResource.PaswdError);
            }
        }
        /// <summary>
        /// 登录并返回用户详情
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_TokenInfo>> LoginInfo([FromBody] VM_Login loginUser)
        {
            return await _AuthService.LoginUserInfo(loginUser);
        }
        /// <summary>
        /// 认证登录（通过验证码和密码进行登录）
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_Token>> LoginAuth([FromBody] VM_Login loginUser)
        {
            var token = await _AuthService.AuthLoginUser(loginUser);
            if (token != null)
            {
                return token;
            }
            else
            {
                return Fail<VM_Token>(SharedResource.PaswdError);
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userRegister"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_Token>> Register(VM_Login_Register userRegister)
        {
            try
            {
                if (string.IsNullOrEmpty(userRegister.Account) || string.IsNullOrEmpty(userRegister.Name))
                    return Fail<VM_Token>("名称不能为空");
                //if (!userRegister.Password.IsPassword())
                //    return Fail<VM_Token>("密码格式不正确(密码至少包含 数字和英文，长度6-20)");
                var reg = await _AuthService.Register(userRegister);
                return reg;
            }
            catch (Exception ex)
            {
                return Fail<VM_Token>(ex.Message);
            }
        }
        /// <summary>
        /// 注册并返回用户详情
        /// </summary>
        /// <param name="userRegister"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_TokenInfo>> RegisterInfo([FromBody] VM_Login_Register userRegister)
        {
            try
            {
                if (string.IsNullOrEmpty(userRegister.Account) || string.IsNullOrEmpty(userRegister.Name))
                    return Fail<VM_TokenInfo>("名称不能为空");
                //if (!userRegister.Password.IsPassword())
                //    return Fail<VM_TokenInfo>("密码格式不正确(密码至少包含 数字和英文，长度6-20)");
                var reg = await _AuthService.RegisterInfo(userRegister);
                return reg;
            }
            catch (Exception ex)
            {
                return Fail<VM_TokenInfo>(ex.Message);
            }
        }
        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<SpActionResult<VM_User>> GetUserInfo()
        {
            return await _AuthService.GetUserInfo();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="changePswd"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public async Task<SpActionResult<bool>> ChangePswd([FromBody] VM_ChangePswd changePswd)
        {
            try
            {
                if (changePswd.Pswd_New == changePswd.Pswd_Old)
                    return Fail<bool>("原密码不能等于新密码");
                //if (!changePswd.Pswd_New.IsPassword())
                //    return Fail<bool>("密码格式不正确(密码至少包含 数字和英文，长度6-20)");
                return await _AuthService.ChangePswd(changePswd);
            }
            catch (Exception ex)
            {
                return Fail<bool>(ex.Message);
            }
        }
        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="forgetPswd"></param>
        /// <returns></returns>
        public async Task<SpActionResult<VM_Token>> ForgetPswd(VM_Login_Forget forgetPswd)
        {
            try
            {
                if (forgetPswd.ConfirmPassword != forgetPswd.Password)
                    return Fail<VM_Token>("两次密码输入不一致");
                //if (!forgetPswd.Password.IsPassword())
                //    return Fail<VM_Token>("密码格式不正确(密码至少包含 数字和英文，长度6-20)");
                return await _AuthService.ForgetPswd(forgetPswd);
            }
            catch (Exception ex)
            {
                return Fail<VM_Token>(ex.Message);
            }
        }
        /// <summary>
        /// 修改手机号码
        /// </summary>
        /// <param name="changePhone"></param>
        /// <returns></returns>
        public async Task<SpActionResult<bool>> ChangePhone(VM_ChangePhone changePhone)
        {
            return await _AuthService.ChangePhone(changePhone);
        }
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="id">TokenId</param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public async Task<SpActionResult<string>> RefreshToken(Guid id)
        {
            var token = await _AuthService.RefreshToken(id);
            var msg = SharedResource.TokenExpire;//多语言
            if (token == null)
            {
                return Fail<string>(msg);
            }
            return Result(token);
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="id">TokenId</param>
        /// <returns></returns>
        [Authorize]
        public async Task LogOut(Guid id)
        {
            await _AuthService.LogOut(id);
        }
        /// <summary>
        /// 查询用户ID
        /// </summary>
        /// <param name="Account"></param>
        /// <returns></returns>
        public async Task<SpActionResult<Guid>> GetUserId(string Account)
        {
            if (string.IsNullOrEmpty(Account))
                return Fail<Guid>("账号(或者手机号、邮箱)不能为空");
            return await _AuthService.GetUserId(Account);
        }
        /// <summary>
        /// 获取最新版本信息
        /// </summary>
        /// <param name="updateAppV"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SpActionResult<VM_AppUpdate>> GetUpdateApp( VM_UpdateAppV updateAppV)
        {
            try
            {
                var aop_service =await _appMService.GetUpdateApp(updateAppV);
                return aop_service;
            }
            catch (Exception ex)
            {
                return Fail<VM_AppUpdate>(ex.Message);
            }
        }
    }
}
